<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="sellerAssign" :disabled="this.sels.length===0">分配营销人员</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleChangeBusiness" :disabled="this.sels.length===0">转化</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="checkedId" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="fullName" label="全名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="120" sortable>
      </el-table-column>
      <!--0表示未分配 1表示跟进 2表示已转化为商机 -1放入线索池-->
      <el-table-column prop="state" label="状态" width="80" sortable>
        <template scope="scope">
          <span v-if="scope.row.state=='0'" style="color: blue">未分配</span>
          <span v-if="scope.row.state=='1'" style="color: gold">跟进中</span>
          <span v-if="scope.row.state=='2'" style="color: green">已转化</span>
          <span v-if="scope.row.state=='-1'" style="color: red">已废弃</span>
        </template>
      </el-table-column>
      <el-table-column prop="company" label="公司" width="80" sortable>
      </el-table-column>
      <el-table-column prop="job" label="职业" width="100" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="200" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="200" sortable>
      </el-table-column>
      <el-table-column prop="mphone" label="移动电话" width="200" sortable>
      </el-table-column>
      <el-table-column prop="address" label="地址" width="200" sortable>
      </el-table-column>
      <el-table-column prop="source" label="来源" width="200" sortable>
      </el-table-column>

      <el-table-column prop="createBy" label="创建人" width="80" sortable>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200" sortable>
      </el-table-column>
      <el-table-column prop="editBy" label="修改人" width="80" sortable>
      </el-table-column>
      <el-table-column prop="editTime" label="修改时间" width="200" sortable>
      </el-table-column>
      <el-table-column prop="description" label="描述" width="200" sortable>
      </el-table-column>
      <el-table-column prop="contactSummary" label="接触总结" width="200" sortable>
      </el-table-column>
      <el-table-column prop="nextContactTime" label="下次接触时间" width="200" sortable>
      </el-table-column>
      <el-table-column prop="seller.username" label="营销人员" width="100" sortable>
      </el-table-column>
      <!--<el-table-column prop="sex" label="性别" width="100" :formatter="formatSex" sortable>
      </el-table-column>-->
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleActivity(scope.$index, scope.row)">参与活动</el-button>
          <el-button size="small" @click="handleFollowUp(scope.$index, scope.row)" :disabled="scope.row.state!=1">跟进</el-button>
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchDel" >批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="query.pageSize" :total="pageInfo.total" style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增或编辑界面
    :visible.sync="outerVisible" 新版本打开对话框
    v-model="clueFormVisible" 老版本打开对话框
    -->
    <!--新增或编辑界面
v-model="saveFormVisible" 老版本用
:visible.sync 新版本用
-->
    <el-dialog title="新增或编辑" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="clue" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名字" prop="name">
          <el-input v-model="clue.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="优惠方式">
          <el-input v-model="clue.preferential_method_id" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="start_date">
          <el-input v-model="clue.start_date" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="结束时间" prop="end_date">
          <el-input v-model="clue.end_date" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="clue.description" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="创建时间时间" prop="create_time">
          <el-input v-model="clue.create_time" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="创建人" prop="create_by">
          <el-input v-model="clue.create_by" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="最近修改时间" prop="edit_time">
          <el-input v-model="clue.edit_time" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="修改人" prop="edit_by">
          <el-input v-model="clue.edit_by" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="参与活动" :visible.sync="activityFormVisible" :close-on-click-modal="false">
      <el-checkbox-group
          v-model="clueActivitys.activityIds"
      >
        <el-checkbox v-for="ac in activityList" :label="ac.id">{{ac.name}}</el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="activityFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="avtivitySubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配营销人员" :visible.sync="sellerFormVisible" :close-on-click-modal="false">
      <el-form :model="clue" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="全称" prop="fullName">
          <el-input v-model="clue.fullName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="clue.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="clue.source" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="clue.description" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="营销人员" prop="seller">
          <el-select v-model="clue.seller" placeholder="请选择" value-key="id">
            <!--key唯一标识
                label选择之后显示到选择框中的值
                value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"-->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="sellerFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="sellerSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="跟进" :visible.sync="followUpFormVisible" :close-on-click-modal="false">
      <el-form :model="clueRemark" label-width="80px">
        <el-form-item label="线索">
          <el-input v-model="clueRemark.clue.fullName" auto-complete="off"readonly></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="noteContent">
          <el-input v-model="clueRemark.noteContent" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="followUpFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="followUpSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="转化商机" :visible.sync="clueBusinessVisible" :close-on-click-modal="false">
      <el-form :model="clueBusiness.clue" label-width="80px"  ref="clueBusinessForm">
        <el-form-item label="姓名">
          <el-input v-model="clueBusiness.clue.fullName"  disabled="disabled" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="clueBusiness.clue.phone" disabled="disabled" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品">
          <el-select v-model="clueBusiness.product" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
               必须要写  value-key="id"
            -->
            <el-option
                v-for="item in products"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.price }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="clueBusinessVisible = false">取消</el-button>
        <el-button type="primary" @click.native="clueBusinessSubmit">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  data() {
    return {
      //分页相关
      query: {
        currentPage: 1,
        pageSize: 10,
        keyword: ''
      },
      pageInfo: {
        total: 0,
        rows: []
      },
      listLoading: false,  //加载圈  默认关闭
      sels: [],//选中的id们  删除用

      clueFormVisible: false,//新增界面是否显示
      clueLoading: false,

      clueFormRules: { //定义必填项
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ]
      },
      //新增界面数据
      clue: {
        id: null,
        fullName: '',
        appellation: '',
        company: '',
        job: '',
        email: '',
        phone: '',
        mphone: '',
        address: '',
        source: null,
        state: null,
        createBy: '',
        createTime: '',
        editBy: '',
        editTime: '',
        description: '',
        contactSummary: '',
        nextContactTime: '',
        seller: {}//营销人员
      },
      employees: [],/*保存员工（营销人员）数据*/
      saveFormVisible: false,//新增或编译界面是否显示
      activityFormVisible: false,//选择活动窗口
      sellerFormVisible: false,//分配营销人员窗口
      followUpFormVisible: false,//跟进窗口
      clueBusinessVisible: false,//转化成商机
      saveLoading: false,
      saveFormRules: {
        name: [
          {required: true, message: '请输入标题名字', trigger: 'blur'}
        ]
      },
      clueActivitys: {
        clueId: null,
        activityIds: []
      },
      activityList: [],
      clueRemark: {
        id: null,
        noteContent: '',
        clue: {}
      },
      clueBusiness: {//商机包含线索和商品才能转化成商机
        clue: {},
        product: {}
      },
      products: []
    }
  },
  methods: {
    //转化成商机
    clueBusinessSubmit(){
      // console.log(this.clueBusiness)
      this.$http.post("/clue/business",this.clueBusiness)
          .then(result=>{
            result = result.data;
            if (result.success){
              this.$message({
                message: '操作成功！',
                type: 'success'
              });
              this.clueBusinessVisible = false;
              this.getClues(); //刷新表格
            }else{
              this.$message({
                message: '转化失败！'+result.message,
                type: 'error'
              });
            }

          })
          .catch(result=>{
            this.$message({
              message: '系统错误！',
              type: 'error'
            });
          })
    },
    //页面刷新  查找事件
    search(){
      //重置当前页为第一页
      this.query.currentPage =1;
      this.getClues();
    },

//获取选中行数据======
    handleCurrentChange(val) {
      this.query.currentPage= val;
      this.getClues();
    },

//获取用户列表===========
    getClues() {
      this.listLoading = true; //发起请求之前显示加载条
      //发起请求获取数据
      this.$http.post("/clue",this.query)
          .then(result =>{
            result = result.data; //{success,result:{}}
            if (result.success){
              this.pageInfo = result.result;
            }else{
              this.$message({
                message: '获取数据失败！'+result.message,
                type: 'error'
              });
            }
            this.listLoading = false;
          })
          .catch(result=>{
            this.$message({
              message: '系统错误！',
              type: 'error'
            });
          })
    },

    //分配营销人员
    sellerAssign(){
      if(this.sels.length>1){
        this.$message({
          message: '请选择一个',
          type: 'error'
        })
      } else{
        //回显
        this.clue = this.sels[0]
        if(this.clue.state!=0){
          this.$message({
            message: '请选择一个未分配的线索',
            type: 'error'
          })
        }else{
          this.getEmployees()
          this.sellerFormVisible = true;
        }
      }
    },

//单项删除事件  index:索引   row:选中行的数据{}=====
    handleDel(index, row){
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;  //开启加载圈
        //获取到id
        let id =  row.id ;
        this.$http.delete("/clue/"+id)
          .then(result => {
            this.listLoading = false; //进入操作成功步骤 关闭加载圈
            result= result.data
            if (result.success){
              this.search() //刷新页面
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            }
              //NProgress.done();
            /*this.$message({
              message: '删除成功',
              type: 'success'
            });*/
            //删除完成获取数据
            /*this.query.currentPage=1;
            this.getClues();*/
          });
          }).catch(result => {
              this.getClues() //重新获取数据  不用返回第一页
              this.$message({
                showClose: true,
                message: '删除失败',
                type: 'error'
              });
            console.log(result)
          });
    },

//修改回显==========
    handleEdit(index, row){
      this.clueFormVisible = true;
      this.clue = Object.assign({}, row); //回显
      this.getClueAll();
      this.getCreate();
      this.getEdit();

    },

//打开新增 会话框界面====
    handleAdd() {
      this.clueFormVisible = true; //打开会话窗口
      this.clue =  { //清空数据
        id:null,
        name: '',
        start_date: '',
        end_date:'',
        description:'',
        create_time:'',
        edit_time:'',
        cost:{},
        create:{},
        edit:{}
      }
      this.getClueAll();
      this.getCreate();
      this.getEdit()
    },

//保存事件==================
    save() {
      this.$refs.clueForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.clueLoading = true;
            let para = Object.assign({}, this.clue);
            //para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            this.$http.put("/clue",para).then((result) => {
              result = result.data;

              if (result.success){
                this.$message({
                  message: '保存成功',
                  type: 'success'
                });

                this.clueFormVisible = false; //关闭对话框

                this.$refs['clueForm'].resetFields(); //重置表单

                this.getClues(); //重新加载数据
        }else{
            this.$message({
              message: '保存失败,'+result.message,
              type: 'error'
            });
        }

              this.clueLoading = false; //关闭加载条
            });
          });
        }
      });
    },

    //获取商品信息
    getProducts(){
      this.$http.get("/product")
          .then(result =>{
            result = result.data;
            if (result.success){
              this.products = result.data;
            }else{
              this.$message({
                message: '获取产品数据失败！'+result.message,
                type: 'error'
              });
            }
          })
          .catch(result=>{
            this.$message({
              message: '系统错误！',
              type: 'error'
            });
          })
    },
    //线索跟进备注
    followUpSubmit(){
      // console.log(this.clueRemark)
      let para = Object.assign({}, this.clueRemark);
      this.$http.put("/clueRemark",para)
          .then(result => {
            result = result.data
            if(result.success){
              //NProgress.done();
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.$refs['saveForm'].resetFields();//重置表单
              this.getClues();//保存完重新获取系统数据
              this.saveFormVisible = false;//关闭对话框
            }else{
              this.$message({
                message: '保存失败',
                type: 'error'
              })
            }
          })
      this.followUpFormVisible = false;
    },
    //提交营销人员分配
    sellerSubmit(){
      console.log(this.clue)
      let para = Object.assign({}, this.clue);
      console.log(para)
      this.$http.post("/clue/assign",para)
          .then(result => {
            result = result.data
            if(result.success){
              //NProgress.done();
              this.$message({
                message: '分配成功',
                type: 'success'
              })
              this.$refs['saveForm'].resetFields();//重置表单
              this.getClues();//保存完重新获取系统数据
              this.saveFormVisible = false;//关闭对话框
            }else{
              this.$message({
                message: '分配失败',
                type: 'error'
              })
            }
          })
          .catch(result=>{
            this.$message({
              message: '分配异常',
              type: 'error'+result.message
            })
          });
      this.sellerFormVisible = false
    },
//查询所有员工 选择部门经理=====
    getClueAll(){
      this.$http.get("/dictionaryitem")
      .then(result=>{
        result = result.data;
        this.clues = result.result;
      })
      .catch(result=>{
        this.$message({
          message: '数据获取失败！,'+result.message,
          type: 'error'
        });
      })
    },

    handleChangeBusiness(){
      if(this.sels.length>1){
        this.$message({
          message: '请选择一个',
          type: 'error'
        })
      } else{
        //回显
        this.clueBusiness.clue = this.sels[0];
        if(this.clueBusiness.clue.state!=1){
          this.$message({
            message: '请选择一个处于跟进状态的线索',
            type: 'error'
          })
        }else{
          this.getProducts()
          this.clueBusinessVisible = true;

          //修改线索状态
          //线索备注
          //添加商机，-选择一个产品
          //添加线索产品

        }
      }
    },
    avtivitySubmit(){
      // console.log(this.clueActivitys)
      this.$http.put("/clue/assoc",this.clueActivitys)
          .then(result => {
            result = result.data
            if(result.success){

              //NProgress.done();
              this.$message({
                message: '成功参加',
                type: 'success'
              })
              this.$refs['saveForm'].resetFields();//重置表单
              this.getClues();//保存完重新获取系统数据
              this.saveFormVisible = false;//关闭对话框
            }else{
              this.$message({
                message: '参加失败',
                type: 'error'
              })
            }
          })
          .catch(result=>{
            this.$message({
              message: '异常',
              type: 'error'+result.message
            })
          });
      this.saveLoading = false;//关闭加载条
    },
    getCreate(){
      this.$http.get("/employee")
          .then(result=>{
            result = result.data;
            this.creates = result.result;
          })
          .catch(result=>{
            this.$message({
              message: '数据获取失败！,'+result.message,
              type: 'error'
            });
          })
    },
    getEdit(){
      this.$http.get("/employee")
          .then(result=>{
            result = result.data;
            this.edits = result.result;
          })
          .catch(result=>{
            this.$message({
              message: '数据获取失败！,'+result.message,
              type: 'error'
            });
          })
    },
    //获取可参与活动
    getActivityList(){
      this.listLoading = true;
      this.$http.post("/activity/list")
          .then(result=>{
            result = result.data
            if(result.success){
              this.activityList = result.data;
            }else {
              this.$message({
                message: '获取活动数据失败！'+result.message,
                type: 'error'
              });
            }
            this.listLoading = false;
          })
          .catch(result=>{
            console.log("出错了"+result.message)
          })
    },
    //显示参与活动窗口
    handleActivity($index, row){
      this.clueActivitys.clueId = row.id
      this.getActivityList();
      this.activityFormVisible=true;
    },


    /*=============批量删除========================*/
    //解析选中的id们  批量删除用
    checkedId(val) {
      //获取到选中的数据们的id
      let ids =  val.map(val=>val.id)
      //console.log(ids,'111')
      //赋值 获取到的 id们 到data中
      this.ids = ids;
    },
    //获取员工
    getEmployees() {
      this.$http.get("/employee")
          .then(result=>{
            result = result.data
            if(result.success){
              this.employees = result.data;
            }else {
              this.$message({
                message: '获取数据失败！'+result.message,
                type: 'error'
              });
            }
          })
          .catch(result=>{
            console.log("出错了"+result.message)
          })
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchDel() {
      let ids = this.ids;
      //判断 未选择 提示用户进行选择
      if (ids.length<1){
        this.$message({
          showClose: true,
          message: '请选择删除的内容!',
          type: 'error'
        });
        return;
      }
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/clue",ids)
            .then(result => {
              this.listLoading = false;

              //删除成功 刷新页面  回到第一页 不然最后一页没有数据了  会显示空白页面
              this.search();

              this.$message({
                message: '删除成功',
                type: 'success'
              });

        });
      }).catch(result=> {
        //删除失败刷新页面
        this.getClues()
        this.$message({
          showClose: true,
          message: '删除失败',
          type: 'error'
        });
        console.log(result)
      });
    }
  },
/*=============批量删除========================*/

  mounted() {
    this.getClues();
  }
}

</script>

<style scoped>

</style>